<?php

$params=array();

################################################################################
#
################################################################################
function get_date($separator)
{
  if (!defined($separator))
    {
      $separator="/";
    }
  
  $now_date = date("Y".$separator."m".$separator."d");
  
  return $now_date;
}

################################################################################
#
################################################################################
function get_time($separator)
{
  if (!defined($separator))
    {
      $separator=":";
    }
  
  $now_time = date("H".$separator."i".$separator."s");
  
  return $now_time;
}

################################################################################
#
################################################################################
function error($msg)
{
  print get_date("/")." ".get_time(":")." [ERROR] " .$msg;
}

################################################################################
#
################################################################################
function info($msg)
{
  print get_date("/")." ".get_time(":")." [INFO] " .$msg;
}

################################################################################
#
################################################################################
function warning($msg)
{
  print get_date("/")." ".get_time(":")." [WARNING] " .$msg;
}

################################################################################
#
################################################################################
function read_file($file)
{
  if (! file_exists($file))
    {
      return 0;
    }
  
  $handle = @fopen($file, "r");
  
  $lines = array();
  
  while (!feof($handle)) 
    {
      $buffer = fgets($handle, 4096);
      $lines[] = $buffer;
    }
  
  return $lines;
}

################################################################################
#
################################################################################
function db_connect($host,$user,$pwd,$sys_dbname,$port)
{
  global $params;
  
  #print_r($params);  
  
  $strhost=$host;
  if($port && $port!=3306)
    $strhost=$strhost.":".$port;
  $conn = @mysql_connect($strhost,$user,$pwd);
  if (!$conn || !@mysql_select_db($sys_dbname,$conn)) 
    {
      return 0;
    }
  
  return $conn;
}

################################################################################
#
################################################################################
function db_close($conn)
{
  return @mysql_close($conn);
}

################################################################################
#
################################################################################
function complzero($str)
{
  //print $str."\n";
  $lenghtofstr=strlen($str);
  //print $lenghtofstr. " ";  
  $index=0;
  for($i=0;$i<(8-$lenghtofstr);$i++)
    {
      $index.=0;
    }
  
  $index.=$str;
  
  return $index;
}

################################################################################
#
################################################################################
function get_cfg($lines)
{
  //$newlines = array();
  
  for ($i=0;$i<sizeof($lines);$i++)
    {
      //if ( preg_match ( '/^\!/', $lines[$i]) != 0 )
      if ( preg_match ( '/^\$/', $lines[$i]) != 0 )
	{
	  //$newlines[] = chop($lines[$i]).chop($lines[$i+1]).chop($lines[$i+2]);
	  $newlines[] = chop($lines[$i]).chop($lines[$i+1]);
	  #print chop($lines[$i+2]). "\n";
	}
    }
  
  if($newlines == 0)
    {
      exit(105);
    }
  
  for ($i=0;$i<sizeof($newlines);$i++) 
    {
      $data = split ("\?",$newlines[$i]);
      //info("Printing r data\n");
      //print_r($data);
      
      $line0 = split (";",$data[0]);
      //info("Printing r line0\n");
      //print_r($line0);
      
      #print $data[3]. "\n";
      
      $comm_ref=trim(ereg_replace("\[\X\=\*\]","*",$line0[1]));
      $cfg[$i]->COMREF=$comm_ref;
      
      $cfg[$i]->PTS="";
      for ($j=2;$j<sizeof($line0);$j++)
        if ($line0[$j] != "**")
	  {
	    $cfg[$i]->PTS[]=$line0[$j];
	  }
      
      $line1 = split (";",$data[1]);
      //info("Printing r line1\n");
      //print_r($line1);
      
      $cfg[$i]->ALGOCODE=$line1[1];
      $algocode[]=$cfg[$i]->ALGOCODE;
      
      if($line1[3] == "**")
        {
          $cfg[$i]->PARAM="N/A";
        }
      else
        {
          $cfg[$i]->PARAM=$line1[3];
        }
      
      $perso_file="";
      $perso_file=split("\\\\",$line1[4]);
      //print_r($perso_file);
      if (preg_match ('/\*\*/',$perso_file[0]) != 0 )
        //if($perso_file[0] == "**********" || $perso_file[0] == "**")
        {
          $cfg[$i]->PERSOFILE="N/A";
        }
      else
        {
          $cfg[$i]->PERSOFILE=$perso_file[2];
        }
      
    } // foreach($newlines as $newline)
  
  return $cfg;
}

################################################################################
#
################################################################################
function create_cfg_file($cfgs)
{
  //print_r($cfgs);
  $newcfg = "";
  
  $newcfg.= "@V1.0;?\n";
  $counter=1;
  //return;
  foreach ($cfgs as $cfg)
    {
      //print_r($cfg);
      # write line 1
      $index=complzero($counter++);
      $newcfg.="!".$index.";**;?\n";
      # write line 2  
      $sizeofpts=sizeof($cfg->PTS);
      #print "sizeofpts ".$sizeofpts."\n";
      $nbcolumn_line2=$sizeofpts+1;
      $newcfg.="$".$nbcolumn_line2.";".ereg_replace("\*","[X=*]",$cfg->COMREF);
      
      #print_r($cfg->PTS);
      //foreach($cfg->PTS as $P);
      //$cfg->PTS[$i]="";
      for($i=0;$i<sizeof($cfg->PTS);$i++)
	{
	  //$strpts.=";".$cfg[$counter]->PTS[$i];
	  //print $cfg->PTS[$i]."\n";
	  if (isset($cfg->PTS[$i]))
	  $newcfg.= ";".$cfg->PTS[$i];
	}
      $newcfg.="?\n";
      # write line 3
      $newcfg.= "&16;".$cfg->ALGOCODE.";***;";
      if($cfg->PARAM == "N/A")
	{
	  $newcfg.="**;";
	}
      else
	{
	  $newcfg.=$cfg->PARAM.";";
	}
      if($cfg->PERSOFILE == "N/A")
	{
	  $newcfg.="**;;**;**;**;**;**;**;**;**;**;**;**;**;**;**?\n";
	}
      else
	{
	  if ( preg_match ( '/mepd/',$cfg->PERSOFILE) != 0 )
	    {
	      $path="\\mepd\\";
	    }
	  else
	    {
	       $path="\\abs\\";
	    }
            #$newcfg.="s:\\mepd\\".$cfg->PERSOFILE.";;**;**;**?\n";
	    $newcfg.="s:".$path.$cfg->PERSOFILE.";;**;**;**;**;**;**;**;**;**;**;**;**;**;**?\n";
	}
      //return;
    }
  $newcfg.= "#**;0;?\n";
  // $newcfg."\n";
  return $newcfg;
}

################################################################################
#
################################################################################
function db_query($qstring,$conn) 
{
  if(!($ret=@mysql_query($qstring,$conn)))
    {
      return 0;
    }
  return $ret;
}

################################################################################
#
################################################################################
function db_fetch_object($qhandle)
{
  return @mysql_fetch_object($qhandle,MYSQL_ASSOC);
}

################################################################################
#
################################################################################
function db_numrows($qhandle)
{
  if ($qhandle) {
    return @mysql_numrows($qhandle);
  } else {
    return 0;
  }
}

################################################################################
#
################################################################################
function parse_args($args)
{
  global $params;
  
  $err=0;
  #print_r($args);
  #print_r($params);

  foreach ($args as $arg)
    {
      if ( ($arg == "-h") || ($arg == "--help"))
	{
	  print_usage($args);
	  exit(0);
	}
    }
  
   #print_r($params);
  
  if (!isset($args[6]))
    {
      error("Missing arguments.\n");
      $err++;
    }
  else
    {
      #$params["DBNAME"]=$args[1];
      #$params["DBLOGIN"]=$args[2];
      #$params["DBPASSWORD"]=$args[3];
      #$params["COMREF"]=$args[4];
      #$params["PERSOFILE"]=$args[5];
      #$params["PTS"]=$args[6];

      $params["EXECUTABLE_NAME"]=array_shift($args);
      $params["DBNAME"]=array_shift($args);
      $params["DBLOGIN"]=array_shift($args);
      $params["DBPASSWORD"]=array_shift($args);
      $params["COMREF"]=array_shift($args);
      $params["PERSOFILE"]=array_shift($args);

      foreach($args as $arg)
	{
	  $params["PTS"][]=array_shift($args);
	}
    }
  
  if ($err>0)
    {
      error("Aborting due to previous error(s). Use -h or --help for usage.\n");
      return 1;
    }
  
     #print $this->INPUTFILE. "\n";

  return 0;
}

################################################################################
#
################################################################################
function print_usage($args)
{
  print "USAGE: ".$args[0]." [-h|--help] <dbname> <dblogin> <dbpasswd> <commercial reference> <perso file> <pts>\n";
}

################################################################################
#
################################################################################
function process()
{
  global $params;
  //print_r($params);

  $err=0;
  $conn=db_connect("localhost",$params["DBLOGIN"],$params["DBPASSWORD"],$params["DBNAME"],"3306");
  if($conn == 0)
    {
      error("Failed to connect to db\n");
      exit(103);
    }
  
  $lines = array();
  $newlines = array();
  $cfg="";
  $counter=0;
  $insert_date=get_date("-")." ".get_time(":");
 
  if (!preg_match("/^([a-zA-Z0-9])+-([\d])[a-zA-Z*]([a-zA-Z0-9-])+$/",$params["COMREF"]))
    {
      error("does not match\n");
      exit(105);
    }
  
  $originalstring = $params["COMREF"];
  $pattern="/^([a-zA-Z0-9]+)-([\d])[a-zA-Z]([a-zA-Z0-9-]+)$/";
  $replacement="$1-$2*$3";
  $params["COMREF"]=preg_replace($pattern, $replacement, $originalstring);
  
  $cfg->COMREF=$params["COMREF"];
  
  $l_pts=$params["PTS"];  

  # get id of pts in list
  foreach($l_pts as $pts)
    {
      $rs=db_query("select id  from pts where pts='$pts'",$conn);
      $row_cnt=$res=mysql_numrows($rs);
      #print "num_rows for pts " .$pts. " : ".$row_cnt."\n";
      if(!$row_cnt)
	{
	  #print "result : PTS ".$pts." unknown.\n";
	  warning("PTS $pts unknown. Adding Into DB ...\n");
	  db_query("insert into pts (pts) values ('$pts')",$conn);
	  $last_inserted_id=mysql_insert_id();
	  $db_pts[$last_inserted_id]=$pts;
	  $counter++;
	  next($l_pts);
	} 
      while($db_data=db_fetch_object($rs))
	{
	  $res=$db_data->id;
          #print "result : ".$res."\n";
	  #$db_pts[$pts]=$db_data['id'];
	  $db_pts[$res]=$pts;
	}
    }
  $cfg->PTS=$db_pts;

  #$cfg->ALGOCODE=$algo_code_id;
  #$cfg->PARAM=$paramBDDUT4_id;
  #$cfg->PERSOFILE="XC19NI21.bin";
  $cfg->PERSOFILE=$params["PERSOFILE"];

  //print_r($cfg);
  
  foreach($cfg->PTS as $pts_key=>$pts_value)
    {
      info("Searching config from ref $cfg->COMREF and pts $pts_value\n");
      #print $cfg->COMREF."\n";
      $sql="SELECT * FROM commercial_reference right JOIN (commercial_reference_pts) ON (commercial_reference.id=commercial_reference_pts.commercial_reference_id) where commercial_reference.ref='".$cfg->COMREF."' and commercial_reference_pts.pts_id= '".$pts_key."' and commercial_reference_pts.status=1";
      #print $sql."\n";
      
      $rs=db_query($sql,$conn);
      $row_cnt=mysql_numrows($rs);
      #print "row_cnt : ".$row_cnt."\n";
      if($row_cnt)
	{
	  warning("Config already exists. Skipping ...\n");
	  $err++;
	  continue;
	}

      warning("Config unknown. Searching ref $cfg->COMREF ...\n");  
      $sql="SELECT * FROM commercial_reference where ref='".$cfg->COMREF."'";
      #print $sql."\n";
	  
      $rs=db_query($sql,$conn);
      $row_cnt=mysql_numrows($rs);
      #print "row_cnt : ".$row_cnt."\n";
      if($row_cnt)
	{
	  warning("Ref $cfg->COMREF already exists. Updating config ...\n");
	  
          # if perso file in config is the same as the one in input
          # then update config
          # else insert new config
	  
	  while($db_data=db_fetch_object($rs))
	    {
	      print "pts : >".$pts_value."<\n";
	      print "pts_id : >".$pts_key."<\n";
	      print "id of comref ".$cfg->COMREF." : >".$db_data->id."<\n";
	      print "perso file in db : >".$db_data->perso_file."<\n";
	      print "perso file in input : >".$cfg->PERSOFILE."<\n";
	      
	      if($cfg->PERSOFILE == $db_data->perso_file)
		{
		  $sql="insert into commercial_reference_pts (commercial_reference_id,pts_id,insert_date) values ($db_data->id,$pts_key,'$insert_date')";
		  print $sql."\n";
		  db_query($sql,$conn);
		  $counter++;
		}
	      else
		{
		  $sql="insert into commercial_reference (ref,simlock,perso_file) values ('$cfg->COMREF','N/A','$cfg->PERSOFILE')";
		  #print $sql."\n";
		  db_query($sql,$conn);
		  $commercial_reference_id=mysql_insert_id();
		  $sql="insert into commercial_reference_pts (commercial_reference_id,pts_id,insert_date) values ($commercial_reference_id,$pts_key,'$insert_date')";
		  #print $sql."\n";
		  db_query($sql,$conn);
		  $counter++;
		  
		} //if($cfg->PERSOFILE == $db_data['perso_file'])
	    } //  while($db_data=db_fetch_object($rs))
	} 
      else
	{
	  warning("Ref $cfg->COMREF does not exists. Inserting ...\n");
	  $sql="insert into commercial_reference (ref,simlock,perso_file) values ('$cfg->COMREF','N/A','$cfg->PERSOFILE')";
	  print $sql."\n";
	  db_query($sql,$conn);
	  $commercial_reference_id=mysql_insert_id();
	  $sql="insert into commercial_reference_pts (commercial_reference_id,pts_id,insert_date) values ($commercial_reference_id,$pts_key,'$insert_date')";
          print $sql."\n";
	  db_query($sql,$conn);
	  $counter++;

	} // if($row_cnt)
    } // foreach($cfg->PTS as $keys=>$pts)
  
  if (!db_close($conn))
    {
      warning("Could not discconnect from the Server.\n");
      return 0;
    }

  return $err;
}

################################################################################
#
################################################################################
function intro()
{
  global $params;
  
  #$params["EXECUTABLE_NAME"]="ftp1.cfg.php";
  
  
  return 0;
}

################################################################################
#
################################################################################
function main($args)
{
  global $params;
  
  if (intro()!=0)
    {
      print "Error while executing intro ... Aborting.\n";
      exit(101);
    }
  
  if (parse_args($args)!=0)
    {
      error("Error while parsing arguments ... Aborting.\n");
      exit(102);
    }
  
  if (process()!=0)
    {
      exit(104);
    }

  #print_r($params);
}

#$argv="";
main($argv);
exit(0);
?>
